//这个是第一个轮播图
var mySwiper1 = new Swiper('#swiper1', {
    direction: 'horizontal', // 垂直切换选项
    loop: true, // 循环模式选项
    // 如果需要分页器
    pagination: {
        el: '.swiper-pagination',
    },
    autoplay: {
        pauseOnMouseEnter: true,
    },
    // 如果需要前进后退按钮
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    },

})
mySwiper1.el.onmouseover = function () {
    mySwiper1.autoplay.stop();
}
mySwiper1.el.onmouseout = function () {
    mySwiper1.autoplay.start();
}
//第二个轮播图
var mySwiper2 = new Swiper('#swiper2', {
    direction: 'horizontal', // 垂直切换选项
    loop: true, // 循环模式选项
    effect: 'fade',
    autoplay: {
        pauseOnMouseEnter: true,
        delay: 1500,
    },

})
mySwiper2.el.onmouseover = function () {
    mySwiper2.autoplay.stop();
}
mySwiper2.el.onmouseout = function () {
    mySwiper2.autoplay.start();
}
mySwiper2.navigation.update();
// 第三个轮播图
var mySwiper3 = new Swiper('#swiper3', {
    direction: 'horizontal', // 垂直切换选项
    loop: true, // 循环模式选项
    autoplay: {
        pauseOnMouseEnter: true,
        delay: 2000,
    },

})
mySwiper3.el.onmouseover = function () {
    mySwiper3.autoplay.stop();
}
mySwiper3.el.onmouseout = function () {
    mySwiper3.autoplay.start();
}
//获取商品数据
require(['./config'], () => {
    require(["aj"], () => {
        getAjax({
                url: "../libs/goods.json"
            })
            .then((data) => {
                let list = JSON.parse(data)
                list = list.slice(0, 81)
                // console.log(list)
                new Pager({
                    data: list,
                    total: 10
                })
            })
    })
})


/**
 * @param {Array} obj.data 传过来要渲染数据
 * @param {Number} obj.total 每一页最多有total条数据
 * 
 */
// 渲染商品数据的类
class Pager {
    constructor(obj) {
        this.data = obj.data
        this.total = obj.total
        this.pageNum = Math.ceil(this.data.length / this.total)
        this.ul = document.querySelector(".pager ul") //分页选项的容器
        this.content = document.querySelector(".content")
        this.span = document.querySelector(".bottom .total span")
        this.init()
    }
    init() {
        // console.log(this.ul, this.content)
        this.pagerRender()
    }
    pagerRender() {
        if (this.pageNum == 1) {
            this.render_1()
        } else if (1 < this.pageNum && this.pageNum < 10) {
            this.render_2()
        } else {
            this.render_3(0)
        }
        this.click()
    }
    //当页数为1的时候渲染样式
    render_1() {
        this.ul.innerHTML = `<li class="show" data-id=1>1</li>`
        let list = this.data
        this.contentRender(list)

    }
    //当页数大于1小于10的时候
    render_2() {
        for (let i = 0; i < this.pageNum; i++) {
            this.ul.innerHTML += `
            <li data-id=${i+1} class="turn">${i+1}</li>
            `
        }
        this.ul.children[0].className += " show"
        let list = this.data.slice(0, this.total)
        this.contentRender(list)
    }
    render_3(start) {
        for (let i = start; i < 10; i++) {
            this.ul.innerHTML += `
            <li data-id=${i+1} class="turn">${i+1}</li>
            `
        }
        this.ul.children[1].className = "show"
        let list = this.data.slice(0, this.total)
        this.contentRender(list)
    }
    contentRender(list) {
        this.content.innerHTML = ""
        list.forEach(item => {
            this.content.innerHTML += `<li>
                                            <img src="${item.img_big_logo}" alt="">
                                            <p class="des">${item.title}</p>
                                            <p class="price">￥:${item.price}</p>
                                            <button class="btn" data-id="${item.goods_id}">加入购物车</button>
                                        </li>`
        });
        this.jisuan()
        this.contentClick(this.data)
    }

    click() {
        this.ul.addEventListener("click", (e) => {
            let target = e.target || e.srcElement
            let rg = /\bshow\b/ //删除样式的正则表达式
            if (target.className == "turn") {

                let id = target.dataset.id //需要根据id的值来选择该渲染哪些数据
                //排他，页码的样式
                for (let i = 0; i < this.ul.children.length; i++) {

                    this.ul.children[i].className = this.ul.children[i].className.replace(rg, "").trim()
                }
                target.className += " show"

                this.idRender(id)
            }

            if (target.className == "pre") {
                let myId
                for (let i = 0; i < this.ul.children.length; i++) {
                    this.ul.children[i]
                }
            }
        }, false)
    }
    idRender(id) {
        if (id * 10 > this.data.length) {
            let list = this.data.slice((id - 1) * 10)
            this.contentRender(list)
        } else {
            let list = this.data.slice((id - 1) * 10, id * 10)
            this.contentRender(list)
        }
    }
    //点击加入购物车
    contentClick(data) {
        this.content.addEventListener("click", (e) => {
            let target = e.target
            if (target.nodeName == "BUTTON") {
                let login = document.querySelector(".login")
                if (login.innerHTML == '<a href="./html/login.html"><span>请登录</span></a>') {
                    alert("请去登录")
                } else {
                    let myId = target.dataset.id
                    let list = JSON.parse(localStorage.getItem("cart")) || []
                    // 通过myId来获取到data里面的goods信息
                    let index = data.findIndex(item => item.goods_id == myId)
                    let goods = data[index]
                    if (list.length) {
                        //找到data里面和myId相同的
                        let res = list.findIndex(item => {
                            return item.goods_id == myId
                        })
                        //通过res的值来判断是否找到匹配的值
                        if (res >= 0) {
                            list[res].cart_number++
                            localStorage.setItem("cart", JSON.stringify(list))

                        } else {
                            goods.cart_number = 1
                            list.push(goods)
                            localStorage.setItem("cart", JSON.stringify(list))
                        }
                    } else {
                        goods.cart_number = 1
                        list.push(goods)
                        localStorage.setItem("cart", JSON.stringify(list))
                    };
                    this.jisuan()
                }

            }

        }, false)
    }
    jisuan() {
        let list = JSON.parse(localStorage.getItem("cart")) || []
        let num = 0
        if (list.length) {
            list.forEach(item => {
                num += item.cart_number
            })
            this.span.innerHTML = num
        }
    }
}

//回到顶部的类
class BackTop {
    constructor() {
        this.btn = document.querySelector(".backTop .icon")
        this.init()
    }
    init() {
        this.click()
    }
    click() {

        this.btn.onclick = () => {
            document.documentElement.scrollTop = 0
        }
    }
}
new BackTop()

//头部定位的类
class Header {
    constructor() {
        this.header = document.querySelector(".header")
        this.hotword = document.querySelector(".header .hotword")
        this.init()
    }
    init() {
        this.scoll()
    }
    scoll() {
        window.onscroll = () => {
            let st = document.documentElement.scrollTop || document.body.scrollTop
            let rg = /\bheader-fixed\b/;
            if (st > 0) {
                if (!rg.test(this.header.className)) {
                    this.header.className += " header-fixed"
                    this.hotword.style.display = "none"
                }
            } else {
                this.header.className = "header"
                this.hotword.style.display = "block"
            }
        }
    }
}
new Header()

//登录刷新功能

require(['./config'], () => {
    require(['myCookie'], () => {
        let login = document.querySelector(".login")
        let quit = document.querySelector(".register")

        function inital() {
            if (getCookie("userName")) {
                login.innerHTML = getCookie("userName")
                quit.style.display = "block"
                // span.innerHTML = getCookie("userName")
            }
        }
        inital()
        quit.onclick = function () {
            quit.style.display = "none"
            login.innerHTML = '<a href="./html/login.html"><span>请登录</span></a>'
            delCookie("userName")
            delCookie("passWord")
        }
    })
})


//限时秒杀功能
class Miaosha {
    constructor() {
        this.timer
        this.init()
    }
    init() {
        this.countDown()
        this.fn()
    }
    countDown() {
        let endDate = new Date("2022/7/30 00:00:00")
        let nowDate = new Date()
        let hTime = document.querySelector(".time-detail span:nth-of-type(1)")
        let mTime = document.querySelector(".time-detail span:nth-of-type(2)")
        let sTime = document.querySelector(".time-detail span:nth-of-type(3)")
        // console.log(hTime, mTime, sTime)
        let seconds = (endDate.getTime() - nowDate.getTime()) / 1000
        if (seconds >= 0) {
            let hours = parseInt(seconds / 3600)
            let m = parseInt(seconds / 60 % 60)
            let s = parseInt(seconds % 60)

            hours < 10 ? hours = "0" + hours : hours
            m < 10 ? m = "0" + m : m
            s < 10 ? s = "0" + s : s

            hTime.innerText = hours
            mTime.innerText = m
            sTime.innerText = s
        } else {
            clearInterval(this.timer)
        }
    }
    fn() {
        this.timer = setInterval(this.countDown, 1000);
    }
}
new Miaosha()